using System.IO;
using System.Text;

using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;

namespace OpenXmlWriter.Packaging
{
  public abstract class OpenXmlPart : OpenXmlPartContainer
  {
    protected OpenXmlPartContainer _openXmlPartContainer;
    protected ContentType _contentType;

    protected OpenXmlPart() : base()
    {
    }

    public virtual void Initialize(OpenXmlPackage openXmlPackage, OpenXmlPartContainer openXmlPartContainer)
    {
      if (openXmlPackage == null)
      {
        _openXmlPackage = openXmlPartContainer.OpenXmlPackage;
      }
      else
      {
        _openXmlPackage = openXmlPackage;
      }
      _openXmlPartContainer = openXmlPartContainer;
    }

    public Stream GetStream()
    {
      return _openXmlPackage.GetStream();
    }

    public virtual void FeedData(Stream sourceStream)
    {
      byte[] buffer = new byte[4096];
      ZipOutputStream destination = (ZipOutputStream) GetStream();
      StreamUtils.Copy(sourceStream, destination, buffer);
      destination.CloseEntry();
    }

    public void WriteContent(string content)
    {
      WriteEntry();
      using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(content)))
      {
        FeedData(ms);
      }
    }

    public void WriteContent(Stream stream)
    {
      WriteEntry();
      using (stream)
      {
        FeedData(stream);
      }
    }

    public abstract string RelationshipType { get; }
    public abstract ContentType ContentType { get; }
  }
}